<?php
/**
 * Created by PhpStorm.
 * User: fusha_000
 * Date: 10-17/0017
 * Time: 15:50
 */

class Sync {

    const ORIGIN_12301  = 1;
    const ORIGIN_16U    = 2;
    /**
     * 同步成功
     */
    const SYNC_OK = 1;
    /**
     * 同步失败
     */
    const SYNC_FAIL = 2;
    const LOG_DIR   = '/var/www/html/new/d/module/sync/logs/';

    static $db          = null;
    static $trans_db    = null;
    static $cur_db      = null;
    static $data_now    = null;
    static $cur_soap    = null;
    static $trans_soap  = null;

    static $setting     = array(
        'cur_origin' => 1,
    );
    static $AttrToChk   = array(
        1 => array(
            'uu_land'       => array(
                'delaytime'=>0,
                'p_type'   => '',
            ),
            'uu_jq_ticket' => array(
                'delaytype'         => 0,
                'cancel_auto_onMin' => 120,
                'order_limit'       => '',
                'order_end'         => '',
            ),
            'uu_land_f'   => array(
                'v_ID_support' => 0,
                'v_time_limit' => 0,
            ),
        ),
        2 => array(
            'uu_land'       => array(
                'p_type'   => '',
            ),
            'uu_jq_ticket' => array(
            ),
            'uu_land_f'   => array(
            ),
        ),

    );
    static $Host        = array(
        1 => 'http://www.12301.cc',
        2 => 'http://www.16u.cc',
    );
    /**
     * set
     *
     * @param $key
     * @param $value
     */
    public static function set($key, $value)
    {
        self::$setting[$key] = $value;
    }

    public static function now()
    {
        if (!is_null(self::$data_now)) {
            return self::$data_now;
        }
        self::$data_now = date('Y-m-d H:i:s');
        return self::$data_now;
    }

    /**
     * 获取uu_land表数据
     * (根据数据库连接获取对应平台的数据)
     * @param $le
     * @param $lid
     * @param $apply_did
     * @return mixed
     */
    public static function getLand($le, $lid, $apply_did)
    {
        //`delaytime`，AND apply_did=$apply_did
        $sql = <<<SQL
SELECT `title`, `tel`, `fax`, `jtype`, `opentime`,`runtime`, `area`, `address`,
`jtzn`,`jdjj`, `bhjq`, `jqts`, `imgpath`,`status`, `px`, `addtime`, `passtime`,
`topic`, `uptime`, `p_type`, `taobao_support`
`attribute`, `terminal`
FROM uu_land WHERE id=$lid  AND apply_did=$apply_did LIMIT 1
SQL;
        $le->query($sql);
        return $le->fetch_assoc();
    }

    public static function getTicket($le, $id, $apply_did)
    {
        //`landid`,
        $sql = <<<SQL
        SELECT `title`,`tprice`, `reb`, `rebp`, `discount`, `delaydays`,
        `uniont`, `mobre`, `px`, `status`, `pay`, `notes`, `ifs`, `storage`,
        `storage_open`, `ddays`, `getaddr`, `smslimit`, `s_limit_up`,
        `s_limit_low`, `buy_limit_up`, `buy_limit_low`, `open_time`,
        `end_time`, `modify_op`, `uuid`
        FROM uu_jq_ticket WHERE id=$id AND apply_did=$apply_did
SQL;
//        echo $sql;
        $le->query($sql);
        return $le->fetch_assoc();
    }

    public static function getLandF($le, $tid)
    {
        //,`v_mobile_support`, `v_ID_support`, `v_time_limit`
        $sql = <<<SQL
    SELECT `lid`, `tid`, `pid`, `p_type`, `dhour`, `confirm_sms`,
    `manual_verify`, `mdays`, `mhour`, `g_fund`, `startplace`,
    `endplace`, `rdays`, `tourist_info`, `ass_station`, `series_model`
     FROM uu_land_f
    WHERE tid=$tid;
SQL;
//        echo $sql;
        $le->query($sql);
        return $le->fetch_assoc();

    }

    public static function AttrChk($db, $tblName, $id=0, $where ='', $title='', $origin=1)
    {
        $origin = !$origin ? self::$setting['cur_origin'] : $origin;
        $ret = array('status'=>'ok');
        $col = '';
//        if($tblName=='uu_land') {
//            $col = ",";
//        }
        $col .= implode(',', array_keys(self::$AttrToChk[$origin][$tblName]));
        if (empty($col)) {
            return $ret;
        }
        $sqlChk = "SELECT $col FROM $tblName WHERE ";
        $sqlChk .= !empty($where) ? $where : "id=$id";
        $sqlChk .= ' LIMIT 1';

        $db->query($sqlChk);
        $row = $db->fetch_assoc();
        $date_now = self::now();

        //TODO::屏蔽套票
        if(isset($row['p_type']) && $row['p_type']=='F') {
            $logWord = $date_now . "|同步数据失败|原始id={$id},{$title}为套票目前无法同步套票产品!";
            self::writeLog($logWord, self::LOG_DIR . 'sync_attr_log.err');
            $ret = array('status'=>'fail', 'msg'=>"{$title}为套票,目前无法同步套票产品");
            return $ret;
        }
        unset($row['p_type']);
//        if (self::$setting['cur_origin']===self::ORIGIN_16U) {
//            return $ret;
//        }
        foreach(self::$AttrToChk[$origin][$tblName] as $attr=>$default) {
            //echo $attr,'----', $default;
            if($row[$attr]!=$default) {
                $logWord = $date_now . "|同步数据失败|原始id={$id},where={$where},msg=[{$tblName}]表{$title}[{$attr}]({$row[$attr]})属性冲突!";
                self::writeLog($logWord, self::LOG_DIR . 'sync_attr_log.err');
                $ret = array('status'=>'fail', 'msg'=>"{$title}[$attr]属性冲突");
                break;
            }
        }
        return $ret;
    }

    /**
     * 取消同步
     *
     * @param integer $mid
     * @param integer $lid
     * @return array
     */
    static function CancelSync($mid, $lid)
    {
        $dbArr     = self::GetMulDB();
        $apply_did = self::Auth($mid);

        $sqlCur = "SELECT apply_did,sync_id,sync_status FROM uu_land WHERE id=$lid AND apply_did=$mid LIMIT 1";
        $dbArr['le']->query($sqlCur);
        $dbArr['le']->fetch_assoc();

        if ($dbArr['le']->f('sync_status')==3) {
            return array('status'=>'fail', 'msg'=>'该产品已取消同步');
        }

        $sqlOtr = "SELECT id,sync_id,sync_status FROM uu_land "
            ."WHERE sync_id=$lid AND apply_did=$apply_did LIMIT 1";
        $dbArr['trans_le']->query($sqlOtr);
//        echo $sqlOtr;
        $dbArr['trans_le']->fetch_assoc();
        $landid = $dbArr['trans_le']->f('id');
        $sync_status = $dbArr['trans_le']->f('sync_status');
//        echo '----' , $sync_status;
        if ($sync_status==4) {
            return array('status'=>'fail', 'msg'=>'该产品已取消同步');
        }


        $sqlCurTickets = "UPDATE uu_jq_ticket SET sync_status=3 WHERE landid=$lid";
        $dbArr['le']->query($sqlCurTickets);
        $sqlCurLand    = "UPDATE uu_land SET sync_status=3 WHERE id=$lid LIMIT 1";
        $dbArr['le']->query($sqlCurLand);

        //todo::票付通平台取消同步，先行平台禁止再次同步。将状态设置为5.
        $sqlOtrTickets = "UPDATE uu_jq_ticket SET sync_status=5 WHERE landid=$landid";;
        $dbArr['trans_le']->query($sqlOtrTickets);
        $sqlOtrLand    = "UPDATE uu_land SET sync_status=5 WHERE id=$landid LIMIT 1";
        $dbArr['trans_le']->query($sqlOtrLand);
        return array('status'=>'ok', 'msg'=>'取消同步成功');
    }

    static function ReSync($mid, $lid)
    {
        $dbArr = self::GetMulDB();
        $apply_did = self::Auth($mid);

        $sqlCur = "SELECT apply_did,sync_id,sync_status FROM uu_land WHERE id=$lid AND apply_did=$mid LIMIT 1";
        $dbArr['le']->query($sqlCur);
        $dbArr['le']->fetch_assoc();

        if ($dbArr['le']->f('sync_status')==1 || $dbArr['le']->f('sync_status')==2) {
            return array('status'=>'fail', 'msg'=>'该产品已同步1');
        }

        $sqlOtr = "SELECT id,sync_id,sync_status FROM uu_land "
            ."WHERE sync_id=$lid AND apply_did=$apply_did LIMIT 1";
        $dbArr['trans_le']->query($sqlOtr);
        $dbArr['trans_le']->fetch_assoc();
        $landid = $dbArr['trans_le']->f('id');
        $sync_status = $dbArr['trans_le']->f('sync_status');
        if (!$landid) {
            return array('status'=>'fail', 'msg'=>'同步失败，之前同步的产品已被删除');
        }
        if ($sync_status==2 || $sync_status==1) {
            return array('status'=>'fail', 'msg'=>'该产品已同步2');
        }


        $sqlCurTickets = "UPDATE uu_jq_ticket SET sync_status=sync_status-2 WHERE landid=$lid";
        $dbArr['le']->query($sqlCurTickets);
        $sqlCurLand    = "UPDATE uu_land SET sync_status=sync_status-2 WHERE id=$lid LIMIT 1";
        $dbArr['le']->query($sqlCurLand);

        $sqlOtrTickets = "UPDATE uu_jq_ticket SET sync_status=sync_status-2 WHERE landid=$landid";;
        $dbArr['trans_le']->query($sqlOtrTickets);
        $sqlOtrLand    = "UPDATE uu_land SET sync_status=sync_status-2 WHERE id=$landid LIMIT 1";
        $dbArr['trans_le']->query($sqlOtrLand);
        return array('status'=>'ok', 'msg'=>'同步成功');
    }

    static function ChkAccount($passport, $pwd) {
        $dbArr = self::GetMulDB();
        if (self::$setting['cur_origin']===self::ORIGIN_12301) {
            $sql="select id,password,sync_id from uu_distributor where passport='{$passport}' or mobile='{$passport}' limit 1";
            $dbArr['trans_le']->query($sql);
            $row = $dbArr['trans_le']->fetch_assoc();
        }
        elseif(self::$setting['cur_origin']===self::ORIGIN_16U) {
            $sql ="select id,password from pft_member where account='{$passport}' or mobile='{$passport}' limit 1";
            $dbArr['trans_le']->query($sql);
            $row = $dbArr['trans_le']->fetch_assoc();
            $sql = "SELECT sync_id FROM pft_member_extinfo WHERE fid={$row['id']} LIMIT 1";
            $dbArr['trans_le']->query($sql);
            $dbArr['trans_le']->fetch_assoc();
            $row['sync_id'] = $dbArr['trans_le']->f('sync_id');
        }
        if ($row['password']!=md5($pwd)) {
            return array('status'=>'fail', 'msg'=>'账号或密码错误，绑定失败');
        }
        if($row['sync_id']>0) {
            return array('status'=>'fail', 'msg'=>'账号已经绑定，无法重复绑定');
        }
        return array('status'=>'ok', 'mid'=>$row['id']);
    }

    static function BindAccount($mid, $passport, $pwd)
    {
        $ret = self::ChkAccount($passport, $pwd);
        if ($ret['status']!='ok') {
            return $ret;
        }
        if (self::$setting['cur_origin']===self::ORIGIN_12301) {
            $sql_cur = "UPDATE pft_member_extinfo SET sync_id={$ret['mid']} WHERE fid={$mid} LIMIT 1";
            $sql_otr = "UPDATE uu_distributor SET sync_id={$mid} WHERE id={$ret['mid']} LIMIT 1";
        }
        elseif(self::$setting['cur_origin']===self::ORIGIN_16U) {
            $sql_cur = "UPDATE uu_distributor SET sync_id={$ret['mid']} WHERE id={$mid} LIMIT 1";
            $sql_otr = "UPDATE pft_member_extinfo SET sync_id={$mid} WHERE fid={$ret['mid']} LIMIT 1";
        }
        $dbArr = self::GetMulDB();
        $dbArr['le']->query($sql_cur);
        $dbArr['trans_le']->query($sql_otr);
        return array('status'=>'ok', 'msg'=>'绑定成功');
    }
    /**
     * 判定/获取绑定平台的会员ID
     *
     * @param int $mid         会员ID
     * @return mixed 会员ID
     */
    public static function Auth($mid=0, $id_type=0)
    {
        $db = self::GetDB();
        if (self::$setting['cur_origin']===self::ORIGIN_12301) {
            $mid = !$mid ? $_SESSION['memberId'] : $mid;
            $sql = "SELECT sync_id AS id FROM pft_member_extinfo WHERE fid=$mid LIMIT 1";
            if ($id_type==1) {
                $sql = "SELECT fid AS id FROM pft_member_extinfo WHERE sync_id=$mid LIMIT 1";
            }
        }
        //SELECT sync_id AS id FROM pft_member_extinfo WHERE fid=184
        elseif (self::$setting['cur_origin']===self::ORIGIN_16U) {
            $mid = !$mid ? $_SESSION['uu_distid'] : $mid;
            $sql = "SELECT sync_id as id FROM uu_distributor WHERE id=$mid LIMIT 1";
            if ($id_type==1) {
                $sql = "SELECT id FROM uu_distributor WHERE sync_id=$mid LIMIT 1";
            }
        }
        //echo $sql;
//        var_dump($db);
        $db->query($sql);
        $db->fetch_assoc();
        $sync_apply_did = $db->f('id');
        $db->free_result();
        if (!$sync_apply_did) {
            $msg = array(1=>'要同步产品请先绑定先行分销平台账号', 2=>'要同步产品请先绑定票付通平台账号');
            exit('{"code":100, "msg":"'.$msg[self::$setting['cur_origin']].'"}');
        }
        return $sync_apply_did;
    }

    /**
     * 同步数据，景区，门票，价格，扩展属性
     *
     * @param $sync_id  主键ID，数据来源平台的id
     * @param int $mid  本平台ID
     * @return array
     */
    public static function CreateLand($sync_id, $mid=0)
    {
        $dbArr      = self::GetMulDB();
        $le         = $dbArr['le'];
        $trans_le   = $dbArr['trans_le'];
//        $apply_did  = self::Auth($mid);//票付通供应商ID
        $sync_apply_did  = self::Auth($mid);//票付通供应商ID
        $apply_did = $mid;
        //判断是不是员工身份
//        $sqlChk = "SELECT lvl,sid FROM uu_distributor WHERE id=$sync_apply_did LIMIT 1";
//        $trans_le->query($sqlChk);
//        $disChk = $trans_le->fetch_assoc();
//        $sync_apply_did =$disChk['lvl']!=2?$sync_apply_did:$disChk['sid'];

        //TODO::检测是否已经同步过
        $sqlChkSync = "SELECT id,title FROM uu_land WHERE sync_id=$sync_id AND apply_did={$apply_did} LIMIT 1";
        $le->query($sqlChkSync);
        $le->fetch_assoc();
        $landid = $le->f('id');
        $title  = $le->f('title');
        $msg    = '产品同步成功';

        if($landid) {
            $ret_ticket = self::CreateTicket($landid, $sync_id, $apply_did, $sync_apply_did, $dbArr);
//            print_r($ret_ticket);
            if($ret_ticket['status']!='ok') {
                $msg = $ret_ticket['msg'];
            }
            return array('status'=>'ok', 'msg'=>$msg .',' .$ret_ticket['msg']);
        }
        //TODO::如果是票付通平台过来的产品需要验证额外的属性
        $ret = self::AttrChk($trans_le, 'uu_land', $sync_id,'', $title, self::ORIGIN_16U);
        if ($ret['status']!='ok') {
            return $ret;
        }

        //TODO::获取对方平台的数据
        $data       = self::getLand($trans_le, $sync_id, $sync_apply_did);
        if (!$data) {
            return array('status'=>'fail', 'msg'=>'同步失败，数据不存在！');
        }
//        print_r($data);
//        echo PHP_EOL . '---------' . PHP_EOL;
        $otr_origin = self::$setting['cur_origin']===self::ORIGIN_16U ? self::ORIGIN_12301 : self::ORIGIN_16U;
        $data['sync_status']  = 2;//被同步
        $data['addtime']      = self::now();//
        $data['sync_id']      = $sync_id;//同步关联ID
        $data['apply_did']    = $apply_did;//供应商ID
        $data['imgpath']      = self::$Host[$otr_origin] . '/' .$data['imgpath'];
        $data['bhjq']         = self::AppendImgHost($data['bhjq'], self::$Host[$otr_origin]);
        $areazax = $data['area'];
        $areazax = explode('|',$areazax);
        $areazax = $areazax[0].'|'.$areazax[1].'|'.'0';
        $sqlzax = "select n_code from pft_area_code_concat where s_code='$areazax'";
        $le->query($sqlzax);
        $le->fetch_assoc();
        $data['areacode'] = $le->f('n_code');        
//        print_r($data);
//        exit;
        //先行平台
        if (self::$setting['cur_origin']===self::ORIGIN_16U) {
            $product = new ProductSync($le);
            $res = $product->AddProduct($data);
            //print_r($res);
        }
        //票付通平台
        elseif (self::$setting['cur_origin']===self::ORIGIN_12301) {
            $product = new ProductSync($le);
            $member  = new \pft\Member\MemberAccount($le, $apply_did);
            $res = $product->AddProduct($data, $member);
        }

        if ($res['status']=='ok') {
            $logWord = self::now() . "|新增同步产品OK,原始lid={$sync_id}";
            self::writeLog($logWord, self::LOG_DIR . 'sync_land_log.log');
            self::UpdateSyncId($trans_le, 'uu_land', $res['lastid'], $sync_id, $sync_apply_did);
            //TODO::同步票数据（价格，扩展属性)
            $ret_ticket = self::CreateTicket($res['lastid'], $sync_id, $apply_did, $sync_apply_did, $dbArr);
            if($ret_ticket['status']!='ok') {
                $msg .= ','.$ret_ticket['msg'];
            }
            return array('status'=>'ok', 'msg'=>$msg);//'同步成功'
        }
        else {
            $logWord = self::now() . "|新增同步产品FAIL,原始lid={$sync_id}".
                ",msg={$res['msg']}";
            self::writeLog($logWord, self::LOG_DIR . 'sync_land_log.err');
            return array('status'=>'fail', 'msg'=>'同步失败'.$res['msg'] );
        }
    }

    /**
     * 同步票类数据
     *
     * @param $landid           landid
     * @param $remote_id        数据来源平台lid
     * @param $apply_did        绑定的供应商ID
     * @param $sync_apply_did   数据来源平台供应商ID（最原始供应商）
     * @param array $dbArr      数据库
     * @param int $id_type      $remote_id类型，0为land表主键,1为ticket表主键
     * @param int $if_chk       是否需要检测景区存在性
     * @return array
     */
    public static function CreateTicket($landid, $remote_id, $apply_did,
                                        $sync_apply_did, $dbArr=array(), $id_type=0, $if_chk=0)
    {
        if (!count($dbArr)) {
            $dbArr = self::GetMulDB();
        }
        $le         = $dbArr['le'];
        $trans_le   = $dbArr['trans_le'];
        if ($if_chk) {
            //TODO::检测景区是否已经同步
            $sql = "SELECT count(*) as cnt FROM uu_land WHERE id=$landid LIMIT 1";
            $le->query($sql);
            $le->fetch_assoc();
            if (!$le->f('cnt')) {
                return array('status'=>'fail', 'msg'=>'产品还未同步无法同步票类，请先同步产品。');
            }
        }

        $ticketTitle= array();
        //todo::根据lid获取tid
        $sql = "SELECT t.id,t.pid,t.sync_id,t.title FROM uu_jq_ticket t LEFT JOIN uu_products p ON p.id=t.pid WHERE p.apply_limit=1 ";
        if ($id_type==0) {
            $sql .= "AND t.landid=$remote_id";
        }
        else {
            $sql .= "AND t.id=$remote_id LIMIT 1";
        }
//        echo $sql;
        $trans_le->query($sql);
        $tids = array();
        while ($row=$trans_le->fetch_assoc()) {
            //如果已经同步过则跳过
            if($row['sync_id']>0) {
                continue;
            }
            $tids[$row['pid']] = $row['id'];
            $ticketTitle[$row['pid']] = $row['title'];
        }

        if(!count($tids)) {
            $logWord = self::now() . "|不存在需要同步的票类或票类已同步|sync_lid={$remote_id}";
            self::writeLog($logWord, self::LOG_DIR . 'sync_ticket_log.log');
            return array('status'=>'ok', 'msg'=>'不存在需要同步的票类或票类已同步');
        }
        //print_r($tids);//exit;
        $soapArr = self::GetMulSoap();
        $date_today = date('Y-m-d');
        $msgArr     = array();
        foreach ($tids as $pid=>$tid) {
            //todo:属性验证
            $ret_chk_t = self::AttrChk($trans_le, 'uu_jq_ticket', $tid,'', $ticketTitle[$pid], self::ORIGIN_16U);
//                print_r($ret_chk_t);
            if($ret_chk_t['status']!='ok') {
                $msgArr[] = $ret_chk_t['msg'];
                continue;
            }
            $ret_chk_f = self::AttrChk($trans_le, 'uu_land_f', 0, "tid=$tid", $ticketTitle[$pid], self::ORIGIN_16U);
            if($ret_chk_f['status']!='ok') {
                $msgArr[] = $ret_chk_f['msg'];
                continue;
            }
            $dataToSync    = self::getTicket($trans_le, $tid, $sync_apply_did);

//            if ($dataToSync['status']!=0) {
//                $logWord = self::now() . "|订单确认属性[status]冲突|tid={$tid}";
//                self::writeLog($logWord, self::LOG_DIR . 'sync_ticket_log.err');
//                return array('status'=>'fail', 'msg'=>'单确认属性[status]冲突');
//            }
            $ExtDataToSync = self::getLandF($trans_le, $tid);
            $dataToSync['apply_did'] = $apply_did;
            $dataToSync['landid']    = $landid;
            $dataToSync['sync_id']   = $tid;
//            print_r($dataToSync);
//            print_r($ExtDataToSync);
//            print_r(self::$AttrToChk['uu_land_f']);
            //TODO::票付通平台增加的属性填入默认值
            if (self::$setting['cur_origin']===self::ORIGIN_12301) {
                $dataToSync     += self::$AttrToChk[self::$setting['cur_origin']]['uu_jq_ticket'];
                $ExtDataToSync  += self::$AttrToChk[self::$setting['cur_origin']]['uu_land_f'];
                //验证时间限制，默认要为空
                unset($dataToSync['order_end']);
            }
            $dataToSync['sync_status'] = 2;//记录数据来源平台
            $product = new ProductSync($le);
//            print_r($dataToSync);//exit;
            $res = $product->AddTickets($dataToSync);
            if ($res['status']=='ok') {
                self::UpdateSyncId($trans_le, 'uu_jq_ticket', $res['lastid'], $tid, $sync_apply_did);
                $logWord = self::now() . "|新增同步票类成功|原始tid={$res['lastid']}";
                self::writeLog($logWord, self::LOG_DIR . 'sync_ticket_log.log');

                //TODO::获取票类生成后的pid
                $sqlGetPid = "SELECT pid FROM uu_jq_ticket WHERE id={$res['lastid']} LIMIT 1";
                $le->query($sqlGetPid);
                $le->fetch_assoc();
                $myPid = $le->f('pid');
                //TODO::变更产品的销售范围及审核状态
                $sqlUpdateStatus = "UPDATE uu_products SET apply_limit=1,p_status=0,verify_time=now() WHERE id={$myPid} LIMIT 1";
                $le->query($sqlUpdateStatus);
                //TODO::同步扩展属性
                $ExtDataToSync['tid'] = $res['lastid'];
                $ExtDataToSync['lid'] = $landid;
                $ExtDataToSync['pid'] = $myPid;
                $sqlInsertToLandF = sqlInsert('uu_land_f', $ExtDataToSync);
                $le->query($sqlInsertToLandF);
                self::writeLog( self::now() ."|同步扩展属性,pid={$myPid},tid={$res['lastid']},lid={$remote_id}", self::LOG_DIR.'sync_land_f.log');
                //TODO::同步价格
                $price_xml = $soapArr['trans_soap']->get_Dynamic_Price_Merge($pid,$date_today, 0);
                $price_arr = simplexml_load_string($price_xml);
                if (count($price_arr)) {
                    foreach ($price_arr as $val) {
                        $enddate    = (string)$val->UUend_date;
                        if($enddate < $date_today) continue;
                        $rid        = (int)$val->UUid;
                        $ptype      = (int)$val->UUptype;
                        $g_price    = $ptype==1 ? (int)$val->UUs_price:(int)$val->UUn_price;
                        $l_price    = (int)$val->UUl_price;
                        $ondays     = (string)$val->UUweekdays;
                        $startdate  = (string)$val->UUstart_date;
                        $storage    = (int)$val->UUstorage;
                        $ret        = $soapArr['cur_soap']->In_Dynamic_Price_Merge($myPid, $startdate,
                            $enddate, $g_price, $l_price, $ptype, 0, $rid, '', $ondays, $storage);
                        self::writeLog( self::now() ."|同步价格,pid={$myPid},return={$ret}", self::LOG_DIR.'sync_price.log');
                    } #EOF FOREACH
                } #EOF IF
            }
            else {
                $logWord = self::now() . "|新增同步票类失败,原始tid=$tid";
                Sync::writeLog($logWord, self::LOG_DIR. 'sync_ticket_log.err');
            }#EOF IF
        }#EOF FOREACH
//        print_r($msgArr);
        if (count($msgArr)) {
            return array('status'=>'not_ok', 'msg'=>implode(',', $msgArr));
        }
        return array('status'=>'ok', 'msg'=>'ok');
    }#EOF FUNCTION


    /**
     * 更新数据来源平台sync_id
     *
     * @param $db 数据库连接
     * @param $tbName 表名
     * @param $syncId 同步后id
     * @param $id     数据来源平台主键ID
     */
    public static function UpdateSyncId($db, $tbName, $syncId, $id, $mid)
    {
        $sql = "UPDATE `$tbName` set sync_id={$syncId},sync_status=1 WHERE id=$id AND apply_did=$mid LIMIT 1";
        self::writeLog(self::now() .'|' .$sql, self::LOG_DIR . 'update_sync_id.sql');
        $db->query($sql);
    }

    /**
     * 记录产品属性变更数据
     *      不记录uu_land表text字段的属性值
     * @param $tbName 表名
     * @param $col_id tid|pid|lid
     * @param $sync_id 同步平台的id
     * @param $dataOld  旧数据
     * @param $dataNew  新数据
     */
    static function LogSync($tbName, $col_id, $sync_id, $dataOld, $dataNew, $le=null)
    {
        $le = is_null($le) ? self::GetDB() : $le;
        $origin = self::$setting['cur_origin'];
        $insertVale = '';
        $now = date('Y-m-d H:i:s');
//        print_r($dataNew);
        foreach($dataNew as $col=>$val) {
            $insertVale .= "('$tbName','$col',$col_id,$sync_id,'{$dataOld[$col]}','{$val}','{$now}',$origin),";
        }
        $insertVale = rtrim($insertVale, ',');
        $sql = "INSERT INTO `sync_data`(`tbname`,`col`,`col_id`,`sync_id`,`chg_old`,".
            "`chg_new`,`log_time`,`origin`) VALUES $insertVale" ;
        //INSERT INTO `sync_data`(`tbname`,`col`,`col_id`,`sync_id`,`chg_old`,`chg_new`,`log_time`,`origin`) VALUES ('uu_products','apply_limit',,,'1','2','2014-10-29 11:25:03',1)
//        echo $sql;
        $le->query($sql);
    }

    /**
     * 变更同步状态
     *
     * @param $logId
     * @param int $status 1成功，2失败
     * @param int $sync_id 另一个平台主键ID
     * @return bool
     */
    public static function ChgSyncStatus($le, $logId, $status=1,$sync_id=0)
    {
        $sql = "UPDATE sync_data SET if_sync={$status},sync_time=now()";
        if ($status==self::SYNC_OK && $sync_id>0) {
            $sql .= ",sync_id=$sync_id";
        }
        $sql .= " WHERE id=$logId LIMIT 1";
        self::writeLog($sql, self::LOG_DIR . 'sync_data.sql');
        $le->query($sql);
        return $le->query($sql);
    }

    /**
     * 记录日志
     *
     * @param $word
     * @param $filepath
     */
    static public function writeLog($word, $filepath) {
        $fp = fopen($filepath,"a");
        flock($fp, LOCK_EX) ;
        fwrite($fp,"\n".$word);
        flock($fp, LOCK_UN);
        fclose($fp);
    }

    static function GetSyncLog($le, $tbname, $col_id=0, $origin=1)
    {
//        $le = self::GetDB($origin);
        $limit = '';
        $sql = "SELECT id,col,chg_new,col_id,sync_id FROM sync_data WHERE tbname='$tbname' AND if_sync=0";
        if ($col_id>0) {
            $sql .= " AND col_id=$col_id";
        }
        if ($origin) {
            $sql .= " AND origin=$origin";
        }
//        echo $sql;
        $le->query($sql);
        $rows = array();
        while($row=$le->fetch_assoc()) {
            $rows[$row['id']] = $row;
        }
        return $rows;
    }

    static function GetDB()
    {
        if (!is_null(self::$db)) {
            return self::$db;
        }
        if (!class_exists('go_sql')) {
            include '/var/www/html/new/conf/le.je';
        }
        self::$db = new go_sql();
        self::$db->connect();
        return self::$db;
    }

    static function GetMulDB()
    {
        if (!is_null(self::$cur_db) && !is_null(self::$trans_db)) {
            return array('le'=>self::$cur_db, 'trans_le'=>self::$trans_db);
        }
        if (!class_exists('trans_go_sql') ) {
            include '/var/www/html/new/conf/trans.le.je';
            self::$trans_db = new trans_go_sql();
            self::$trans_db->connect();
        }
        if ( !class_exists('go_sql') ) {
            include '/var/www/html/new/conf/le.je';
            self::$cur_db = new go_sql();
            self::$cur_db->connect();
        }
        return array('le'=>self::$cur_db, 'trans_le'=>self::$trans_db);
    }

    /**
     * 获取mysql插入的最后ID，避免mysql_insert_id()函数引发的问题
     * @return mixed
     */
    static function LastInsertID()
    {
        $db = self::GetDB();
        $sl = 'SELECT LAST_INSERT_ID() as lastid';
        $db->query($sl);
        $db->fetch_assoc();
        return $db->f('lastid');
    }

    static function GetMulSoap()
    {
        if (!is_null(self::$cur_soap) && !is_null(self::$trans_soap)) {
            return array('cur_soap' => self::$cur_soap, 'trans_soap' => self::$trans_soap);
        }

        $ac = '16ucom';
        $pw = 'c33367701511b4f6020ec61ded352059';

        if (self::$setting['cur_origin']===self::ORIGIN_12301) {
            self::$cur_soap = new SoapClient(null, array(
                "location" => "http://localhost/open/openService/pft_insideMX.php",
                "uri" => "www.16u.com?ac_16u={$ac}|pw_16u={$pw}|auth_16u=true"));
            self::$trans_soap = new SoapClient(null, array(
                "location" => "http://open.16u.com/openService/s_insideMX.php",
                "uri" => "www.16u.com?ac_16u={$ac}|pw_16u={$pw}|auth_16u=true"));
        }
        else {
            self::$trans_soap = new SoapClient(null, array(
                "location" => "http://open.12301.cc/openService/pft_insideMX.php",
                "uri" => "www.16u.com?ac_16u={$ac}|pw_16u={$pw}|auth_16u=true"));

            self::$cur_soap = new SoapClient(null, array(
                "location" => "http://localhost/open/openService/s_insideMX.php",
                "uri" => "www.16u.com?ac_16u={$ac}|pw_16u={$pw}|auth_16u=true"));
        }
        return array('cur_soap' => self::$cur_soap, 'trans_soap' => self::$trans_soap);
    }

    /**
     * 修改描述信息中的图片地址
     *
     * @param $str  文本
     * @param $host host
     * @return mixed
     */
    static function AppendImgHost($str, $host) {
        $str = htmlspecialchars_decode($str);
        preg_match_all("/<img(.*)(src=\"[^\"]+\")[^>]+>/isU", $str, $arr);
        $search = array();
        $replace = array();
        for($i=0,$j=count($arr[0]); $i<$j; $i++){
            if(strpos($arr[2][$i], 'http://')===false) {
                $src = str_replace('src="', "src=\"{$host}", $arr[2][$i]);
            }
            else {
                $src = $arr[2][$i];
            }
            $search[] = $arr[0][$i];
            $replace[] = "<img " .$src." />";
        }
        $str = str_replace($search, $replace,$str);
        return htmlspecialchars($str);
    }

    /**
     * 消息通知
     *
     * @param array $data
     * @return string
     */
    static function Notify(Array $data)
    {
        return true;
    }
} 